<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/common/header.jsp"%>
<script type="text/javascript" src="../../js/security/menu/menuTree.js"></script>
<script type="text/javascript" src="../../js/security/resSingleSelect.js"></script>
<script type="text/javascript">

Ext.onReady(function(){
    Ext.BLANK_IMAGE_URL = '<c:url value="/js/ext/images/default/s.gif"/>';
    Ext.QuickTips.init();
    Ext.SERVER = '<c:url value="/"/>';
    Ext.parentNode = 'undefined';
    Ext.nowNode = 'undefined';
    
    // ------------ 得到url参数-------------------------   
    function GetUrlParms()    
    {
         var args=new Object();   
         var query=location.search.substring(1);//获取查询串   
         var pairs=query.split("&");//在逗号处断开   
         for(var    i=0;i<pairs.length;i++)   
         {   
             var pos=pairs[i].indexOf('=');//查找name=value   
             if(pos==-1)   continue;//如果没有找到就跳过   
             var argname=pairs[i].substring(0,pos);//提取name   
             var value=pairs[i].substring(pos+1);//提取value   
             args[argname]=decodeURI(value);//存为属性   
        }
         return args; 
    }
    
    // ---------------------- West: Role Tree   -------------------------
    var params = GetUrlParms();
    /************************      初始化       ******************************/
    // 初始化菜单树
    MenuTree.init(-1, '根节点');
    // ------------ form action -------------------------    
       var menuFormLoadAction = new Ext.Action({
        text: '取消更改',
        handler: function(aId){
            var idValue = '';

            if (Ext.type(aId) == 'number') {
                idValue = aId;
            }
            else {        
                var treeNode = menuTree.getSelectionModel().getSelectedNode();
                if(treeNode && treeNode.id != -1) {
                  idValue = treeNode.id;
                }
            }  
            menuForm.getForm().reset();
            menuForm.getForm().load({
                url: '<c:url value="/menu/menuManage.do"/>',
                method: 'get',
                params: {
                    id: idValue,
                    action: 'menuForm_load'
                },
                waitMsg: 'loading...',
                success: function(aResponse, aOptions){
                },
                failure: function() {
                    Ext.Msg.alert('提示', '读取数据失败！');                               
                }
            });
              
        }
    });
    var menuFormSaveAction = new Ext.Action({
        text: '保存',
        handler: function(){
            if(menuForm.getForm().isValid()){
                
                Ext.nowNode = menuTree.getSelectionModel().getSelectedNode();
                if(Ext.curState!=undefined&&Ext.curState != 'add') Ext.nowNode.remove();
                var treeNodeId = menuForm.getForm().findField('menuForm_parentId').getValue();
                if (treeNodeId) {
                   Ext.parentNode = menuTree.getNodeById(treeNodeId);
                }
                menuForm.getForm().submit({
                    url: '<c:url value="/menu/menuManage.do" />',
                    params: {
                        treeNodeId: treeNodeId,    
                        action: 'menuForm_save'
                    },
                    waitTitle: '请等待',
                    waitMsg: '正在处理数据...',
                    timeout: 10,
                    success: function(aForm, aAction){
                        if (Ext.parentNode!='undefined') { 
                            if(Ext.parentNode.isLeaf()){
                                Ext.parentNode.parentNode.reload();
                            }else{
                                Ext.parentNode.reload();
                            }
                            if(Ext.nowNode==null){
                                idValue = (menuTree).root.id;
                            }else{
                                idValue = Ext.nowNode.id;
                            }
                        } else {
                            (menuTree).root.reload();
                            idValue = (menuTree).root.id;
                        }      
			            menuForm.getForm().reset();
			            menuForm.getForm().load({
			                url: '<c:url value="/menu/menuManage.do"/>',
			                method: 'get',
			                params: {
			                    id: idValue,
			                    action: 'menuForm_load'
			                },
			                waitMsg: 'loading...',
			                success: function(aResponse, aOptions){
			                },
			                failure: function() {
			                    Ext.Msg.alert('提示', '读取数据失败！');                               
			                }
			            });                      
                    },
                    failure: function() {
                        Ext.Msg.alert('提示', '保存失败！');                             
                    }
                });
            }
        }
    });
    
    // --------------- 调用菜单选择页面后执行的回调方法 -------------------
    function menuSave (){  
        if (MenuTree.menuNode != 'undefined') {
	        menuForm.getForm().load({
                url: '<c:url value="/menu/menuNameGet.do"/>',
                method: 'get',
                params: {
                    id: MenuTree.menuNode,
                    action: 'menuText_load'
                },
                waitMsg: 'loading...',
                success: function(aResponse, aOptions){
                },
                failure: function() {
                    Ext.Msg.alert('提示', '菜单选择错误！');                             
                }
            });
        }
    }
    MenuTree.window.on("hide",function(){    
        menuSave (); 
    });           
    var menuSingleSelectAction = new Ext.Action({
        text: '选择菜单',
        handler: function(){            
            MenuTree.menuTree.getRootNode().reload();
            MenuTree.window.show();
        }
    });
    // resource
    // 应用系统下拉选项框
    var appList = new Ext.form.ComboBox({
        id: 'form0_appList',
        name: 'appList',
        hiddenName: 'appList',
        fieldLabel: '请选择系统',
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'remote',
        store: new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: Ext.SERVER+'security/res/resManage.do?action=form0_appList_load'
            }),
            reader: new Ext.data.JsonReader({
                root: 'data',
                id: 'key'
                }, 
                ['key', 'value']
            )
        }),
        valueField: 'key',
        displayField: 'value',
        listeners: {
            select: function(combo,record,index){
                 SingleResSingleSelectTreeUI.appId = combo.getValue();   
                 SingleResSingleSelectTreeUI.resMentTree.root.reload();        
            }
        }
    });
    appList.store.load();
    // 重载一下资源的window，添加combox
    Ext.apply(SingleResSingleSelectTreeUI,{
        windowF: function(){
                this.window = new Ext.Window({
                    closable: false,
                    width:300, height: 300,
                    layout: 'fit',
                    tbar:[this.select, this.channel, appList],
                    items: [this.resMentTree]
                });
        }
    });
    SingleResSingleSelectTreeUI.init();
    SingleResSingleSelectTreeUI.window.on("hide",function(){
        if(SingleResSingleSelectTreeUI.resMentTree.curNode!='undefined'){
            menuForm.getForm().findField('aresName').setValue(SingleResSingleSelectTreeUI.resMentTree.curNode.attributes.text);
            menuForm.getForm().findField('smenReourceId').setValue(SingleResSingleSelectTreeUI.resMentTree.curNode.attributes.id);
        }
    });
    // ------------------ form -------------------------    
    var menuForm = new Ext.form.FormPanel({
        id: 'menuForm',
        region:'center',
        height:200,
        buttonAlign:'center',
        bodyStyle: 'padding:5px',
        frame: true,
        layout: 'fit',
        items: [{
            layout: 'form',
            items: [
                        {
                            name: 'id',
                            inputType: 'hidden',
                            fieldLabel: '*编号',
                            xtype: 'textfield'
                        },
                        {
                            name: 'menuForm_parentId',
                            inputType: 'hidden',
                            fieldLabel: '*上级菜单id',
                            xtype: 'textfield'
                        },
                        {
                            name: 'smenCaption',
                            fieldLabel: '*菜单名称',
                            allowBlank: false,
                            xtype: 'textfield'
                        },
                        {
				            layout: 'column',
				            items: [
				                    {
				                        columnWidth: .34,
				                        layout: 'form',
				                        labelWidth: 100,
				                        defaults: {
				                            width: 60,
				                            msgTarget: 'side'
				                        },
				                        items: [
				                            {
					                            name: 'menuForm_parentName',
					                            fieldLabel: '*上级菜单',
					                            allowBlank: false,
					                            xtype: 'textfield',
					                            disabled: true,
					                            width: 180
					                        }
				                        ]
				                    },
				                    {
				                        columnWidth: .66,
				                        layout: 'form',
				                        labelWidth: 100,
				                        defaultType: 'button',
				                        defaults: {
				                            width: 180,
				                            msgTarget: 'side'
				                        },
				                        items: [
				                            menuSingleSelectAction
				                        ]
				                    }
				                ]
				        },                       
			            {
                            name: 'aresName',
                            fieldLabel: '*关联资源',
                            allowBlank: false,
                            xtype: 'trigger',
                            triggerClass: 'x-form-search-trigger',
                            onTriggerClick:  function(eventObject){
                                SingleResSingleSelectTreeUI.appId = appList.getValue();   
                                SingleResSingleSelectTreeUI.window.show();
                            },
                        },                       
                        {
                            name: 'smenReourceId',
                            fieldLabel: '*关联资源ID',
                            allowBlank: false,
                            inputType: 'hidden',
                            xtype: 'textfield'
                        },                       
                        {
                            name: 'smenIndex',
                            fieldLabel: '排列索引',
                            allowBlank: false,
                            xtype: 'numberfield'
                        }
                    ]
        }],
        buttons: [
            menuFormSaveAction,
            menuFormLoadAction
        ]
    });

    var menuTreeNewAction = new Ext.Action({
        text: '新增',
        iconCls: 'btn_add',
        handler: function(){
            Ext.curState = 'add';
            var treeNode = menuTree.getSelectionModel().getSelectedNode();
            if(treeNode){
                menuForm.getForm().reset();
                menuForm.getForm().load({
                url: '<c:url value="/menu/menuNameGet.do"/>',
                method: 'get',
                params: {
                    id: treeNode.id,
                    action: 'menuText_load'
                },
                waitMsg: 'loading...',
                success: function(aResponse, aOptions){
                },
                failure: function() {
                    Ext.Msg.alert('提示', '菜单选择错误！');                             
                }
            });
            } else {
                Ext.Msg.alert('提示', '请选择菜单！');    
            }
        }
    });
    
    
    var menuTreeEditAction = new Ext.Action({
        text: '编辑',
        iconCls: 'btn_edit',
        disabled: true,
        handler: function(){
            Ext.curState = 'edit';
            var treeNode = menuTree.getSelectionModel().getSelectedNode();
            if(treeNode){
                menuForm.getForm().reset();
                menuFormLoadAction.execute(treeNode.id);
            } else {
                Ext.Msg.alert('提示', '请选择菜单！');  
            }
        }
    });
    
    var menuTreeReloadAction = new Ext.Action({
        text: '刷新',
        iconCls: 'x-tbar-loading',
        disabled: false,
        handler: function(){
            var tree = Ext.getCmp('menuTree');
            tree.body.mask('数据加载中……', 'x-mask-loading');
            tree.root.reload();
            tree.root.collapse(true, false);
            tree.root.expand(false,false,function(){ 
                                tree.body.unmask();//全部展开之后让蒙版消失  
             }); 
        }
    });

    var menuTreeDeleteAction = new Ext.Action({
        text: '删除',
        iconCls: 'btn_del',
        disabled: true,
        handler: function(){
            Ext.curState = 'delete';
            Ext.nowNode = menuTree.getSelectionModel().getSelectedNode();
            if(Ext.nowNode){
                Ext.nowNode.expand(false,false,function(){ 
	                if (Ext.nowNode.childNodes && Ext.nowNode.childNodes.length>0) { 
	                    Ext.Msg.alert('提示', '不能删除菜单：<' + Ext.nowNode.text + '>此菜单尚包含下级菜单 ！');   
	                    return;
	                }
	                Ext.Msg.confirm('删除确认', '是否删除选择的菜单:' + Ext.nowNode.text + ' ？', function(aButton){
	                    if (aButton == 'yes'){
	                        Ext.Ajax.request({
	                            url: '<c:url value="/menu/menuManage.do"/>',
	                            params: {
	                                action: 'menuTree_delete',
	                                id: Ext.nowNode.id                        
	                            },
	                            success: function(response, action){
	                                text = response.responseText;
                                    json = Ext.decode(text);
                                    if(json.success == false){  
                                        Ext.Msg.alert('提示', json.message);
                                    } else {
	                                
		                                if (Ext.nowNode.parentNode) {
		                                    idValue = Ext.nowNode.parentNode.id;
		                                    Ext.nowNode.parentNode.reload();  
		                                } else {
		                                    idValue = menuTree.root.id;
		                                    menuTree.root.reload();
		                                }    
		                                menuForm.getForm().reset();
				                        menuForm.getForm().load({
				                            url: '<c:url value="/menu/menuManage.do"/>',
				                            method: 'get',
				                            params: {
				                                id: idValue,
				                                action: 'menuForm_load'
				                            },
				                            waitMsg: 'loading...',
				                            success: function(aResponse, aOptions){
				                            },
				                            failure: function() {
				                                Ext.Msg.alert('提示', '读取数据失败！');                               
				                            }
				                        });                       
		                                Ext.Msg.alert('提示', '删除成功。');
	                                }
	                            },
				                failure: function(response, action) {
				                    text = response.responseText;
                                    json = Ext.decode(text);
				                    if(json.success == false){  
                                        Ext.Msg.alert('提示', json.msg);
				                    } else {
				                        Ext.Msg.alert('提示', '读取失败');
				                    }                             
				                }                     
	                        });
	                    }
	                });
             });
            } else {
                Ext.Msg.alert('提示', '请选择菜单！');   
            }
        }
    });

    function menuTreeUpdateAction (){
            var treeNode = menuTree.getSelectionModel().getSelectedNode();
            var treeNodeId = '';
            if(treeNode && treeNode.id != -1){
                treeNodeId = treeNode.id;
                menuTreeEditAction.enable();
                menuTreeDeleteAction.enable();
                menuForm.getForm().reset();
                menuFormLoadAction.execute(treeNodeId);
            }else{
                menuTreeEditAction.disable();
                menuTreeDeleteAction.disable();
            }  
    };

    var menuTree = new Ext.tree.TreePanel({
        id: 'menuTree',
        region:'west',
        width: 300,
        height: 260,
		autoScroll: true,
		border: false,
		containerScroll: true,
		loader: new Ext.tree.TreeLoader(),
		rootVisible: true,
		lines: false,
		singleExpand: true,
		useArrows: true,
		root:new Ext.tree.AsyncTreeNode({
            id :'-1',
            text: '根节点'
        }),
		loader: new Ext.tree.TreeLoader({
			url: '<c:url value="/menu/expendMenuTree.do"/>'
		}),
        listeners: {
            click: function(node){
               MenuTree.menuTree.specialNode = node;// 指定特殊（无法展开，选择）的节点
            }
        },
        tbar: [
            menuTreeNewAction,
            menuTreeReloadAction,
            menuTreeDeleteAction
        ]
	})
	
    menuTree.getSelectionModel().addListener(
        'selectionchange',
        menuTreeUpdateAction
    );

    // --------------- viewport --------------------
    var viewport = new Ext.Viewport({
        layout: 'border',
        border: false,
        items: [
            menuTree,
            menuForm
        ]
    });

    // --------------- load data -------------------
});
</script>
<%@ include file="/WEB-INF/views/common/footer.jsp"%>
